package com.algorithm;

public class TwoSearch {

    public static int biSearch(int[] array, int a) {
        int lo = 0;
        int hi = array.length - 1;
        int mid;
        while (lo < hi) {
            //中间位置
            mid = (lo + hi) / 2;
            if (array[mid] == a) {
                return mid + 1;
                //向右查找
            } else if (array[mid] < a) {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return -1;
    }

    /**
     * 二分查找
     *
     * @param args
     */
    public static int twoSearch(int[] arr, int a) {
        int mid;
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            mid = (end + start) / 2;
            if (a > arr[mid]) {
                start = mid + 1;
            } else if (a < arr[mid]) {
                end = mid - 1;
            } else {//向左查找
                return mid + 1;
            }
        }
        return -1;
    }

    /**
     * 冒泡排序
     *
     * @param arr
     * @return
     */
    public static int[] sort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            for (int j = 0; j < arr.length - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }

    public static void main(String[] args) {
        int[] arr = {2, 5, 3, 8, 4, 6, 9, 1};
        int[] bubble = sort(arr);
        int i = twoSearch(bubble, 9);
        System.out.println("输出二分查找后的下标：" + i);
    }

}
